package com.siyuanren.gcocp.config;

import cn.hutool.core.io.FileUtil;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.menu.WxMenu;
import me.chanjar.weixin.common.bean.menu.WxMenuButton;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.util.crypto.SHA1;
import me.chanjar.weixin.mp.api.WxMpConfigStorage;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.menu.WxMpGetSelfMenuInfoResult;
import me.chanjar.weixin.mp.bean.menu.WxMpMenu;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import me.chanjar.weixin.mp.bean.result.WxMpUserList;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author guwr
 * @date 2018/4/4
 */
public class MenuConfigBack {

    /**
     * 定义菜单结构
     *
     * @return
     */
    private static WxMenu getMenu() {

        MainConfig mainConfig = new MainConfig("wxf51bffd7272ef8ff", "eeb1238e5b03a7c4193ac674fc1b7a46", "siyuanren", "vRGDnPuhDKNIiye04Y1w2pf0BZI51SESyXg6jRbaWFV");
        WxMpService wxMpService = mainConfig.wxMpService();


        WxMenu menu = new WxMenu();
        WxMenuButton button1 = new WxMenuButton();
        button1.setType(WxConsts.MenuButtonType.VIEW);
        button1.setName("开始学习");
        button1.setAppId(mainConfig.appId);
        button1.setUrl("http://wenren.gcocp.com/wx/authorize");
//        button1.setUrl(wxMpService.oauth2buildAuthorizationUrl("http://wenren.gcocp.com/wx/index", WxConsts.OAuth2Scope.SNSAPI_USERINFO, ""));
//
//        WxMenuButton button2 = new WxMenuButton();
//        button2.setName("我是卖家");
//
//        WxMenuButton button21 = new WxMenuButton();
//        button21.setType(WxConsts.MenuButtonType.VIEW);
//        button21.setName("我的订单");
//        button21.setUrl(wxMpService.oauth2buildAuthorizationUrl("", "snsapi_base", ""));
//
//        WxMenuButton button22 = new WxMenuButton();
//        button22.setType(WxConsts.MenuButtonType.VIEW);
//        button22.setName("收入统计");
//        button22.setUrl(wxMpService.oauth2buildAuthorizationUrl("", "snsapi_base", ""));
//
//        WxMenuButton button23 = new WxMenuButton();
//        button23.setType(WxConsts.MenuButtonType.VIEW);
//        button23.setName("发布商品");
//        button23.setUrl(wxMpService.oauth2buildAuthorizationUrl("", "snsapi_base", ""));
//
//        WxMenuButton button24 = new WxMenuButton();
//        button24.setType(WxConsts.MenuButtonType.VIEW);
//        button24.setName("商品管理");
//        button24.setUrl(wxMpService.oauth2buildAuthorizationUrl("", "snsapi_base", ""));
//
//        button2.getSubButtons().add(button21);
//        button2.getSubButtons().add(button22);
//        button2.getSubButtons().add(button23);
//        button2.getSubButtons().add(button24);

//		WxMenuButton button3 = new WxMenuButton();
//		button3.setType(MenuButtonType.CLICK);
//		button3.setName("使用帮助");
//		button3.setKey("help");

        menu.getButtons().add(button1);
//        menu.getButtons().add(button2);
//		menu.getButtons().add(button3);

        return menu;
    }

    /**
     * 运行此main函数即可生成公众号自定义菜单，注意要修改MainConfig构造方法行代码的对应四个参数为实际值
     *
     * @param args
     */
    public static void main(String[] args) throws Exception {
        MainConfig mainConfig = new MainConfig("wxf51bffd7272ef8ff", "eeb1238e5b03a7c4193ac674fc1b7a46", "siyuanren", "vRGDnPuhDKNIiye04Y1w2pf0BZI51SESyXg6jRbaWFV");
        WxMpService wxMpService = mainConfig.wxMpService();
//        WxJsapiSignature jsapiSignature = wxMpService.createJsapiSignature("http://wenren.gcocp.com/wx/index");
//        System.out.println("jsapiSignature = " + jsapiSignature);
//        getJsapiTicket(wxMpService);

//        genSignature(wxMpService);
//        menu(wxMpService);
//        testSendTemplateMsg(wxMpService);
//        menuGet(wxMpService);
        userList(wxMpService);
//        userInfoSingle(wxMpService);
//        userInfo(wxMpService);
    }

    private static void userInfo(WxMpService wxMpService) throws Exception {
        WxMpUser wxMpUser = wxMpService.getUserService().userInfo("oEwcg1rVp-JDml_XJ5XjOEXLzej0");
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                .templateId("0-QZOZ6yywdxLoQNoCQTxPwto4LW-Gqwx18YSR-wWiw")
                .url("https://st.h5.xiaoe-tech.com/st/24ZHGmTFD")
                .build();
        templateMessage.addData(new WxMpTemplateData("first", "魏霞老师21天成长课程-青少年问题专讲，明天开讲！", "#2a75ed"))
                .addData(new WxMpTemplateData("keyword1", "《读懂少年心—21天教你如何陪伴孩子度过青春期》", "#2a75ed"))
                .addData(new WxMpTemplateData("keyword2", "2018年5月30日", "#2a75ed"))
                .addData(new WxMpTemplateData("remark", "点击进入课程", "#2a75ed"));
        templateMessage.setToUser("oEwcg1sVH-NYI5vsk-i9voI7DEBA");
        wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
    }

    private static void userList(WxMpService wxMpService) throws Exception {
        WxMpUserList list = wxMpService.getUserService().userList("oEwcg1uC4V5m35xZBg5cImblT8VM");
        int i = 0;
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                .templateId("0-QZOZ6yywdxLoQNoCQTxPwto4LW-Gqwx18YSR-wWiw")
                .url("https://st.h5.xiaoe-tech.com/st/24ZHGmTFD")
                .build();
        templateMessage.addData(new WxMpTemplateData("first", "魏霞老师21天成长课程-青少年问题专讲，明天开讲！", "#2a75ed"))
                .addData(new WxMpTemplateData("keyword1", "《读懂少年心—21天教你如何陪伴孩子度过青春期》", "#2a75ed"))
                .addData(new WxMpTemplateData("keyword2", "2018年5月30日", "#2a75ed"))
                .addData(new WxMpTemplateData("remark", "点击进入课程", "#2a75ed"));
//        List<String> writeAttr = new ArrayList();
        for (String s : list.getOpenids()) {
            templateMessage.setToUser(s);
            wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
            i++;
            System.out.println(i + "," +s);
        }
//        FileUtil.writeUtf8Lines(writeAttr, new File("D:\\wx.txt"));
    }

    private static void userInfoSingle(WxMpService wxMpService) throws Exception {
        WxMpUser wxMpUser = wxMpService.getUserService().userInfo("oEwcg1rX1EaQfoaFdGSONTKCYhpA");
        System.out.println("wxMpUser = " + wxMpUser);
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                .toUser(wxMpUser.getOpenId())
                .templateId("0-QZOZ6yywdxLoQNoCQTxPwto4LW-Gqwx18YSR-wWiw")
                .url("http://timmystyle.com/a/af6830b17ab39507e0fb50556aabadfb")
                .build();
        templateMessage.addData(new WxMpTemplateData("first", "魏霞老师免费微课—青春期问题专讲，明天开讲！", "#2a75ed"))
                .addData(new WxMpTemplateData("keyword1", "《如何处理孩子青春期的问题，决定孩子一生的结局》", "#2a75ed"))
                .addData(new WxMpTemplateData("keyword2", "2018年5月18日晚7:30", "#2a75ed"))
                .addData(new WxMpTemplateData("remark", "点击详情免费进群听课！", "#2a75ed"));
        String msgId = wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
    }


    private static void menuGet(WxMpService wxMpService) throws Exception {
        WxMpMenu wxMpMenu = wxMpService.getMenuService().menuGet();
        System.out.println("wxMpMenu = " + wxMpMenu);
    }

    private static void menu(WxMpService wxMpService) throws Exception {
        WxMpGetSelfMenuInfoResult selfMenuInfo = wxMpService.getMenuService().getSelfMenuInfo();
        System.out.println("selfMenuInfo = " + selfMenuInfo);
        wxMpService.getMenuService().menuDelete();
        wxMpService.getMenuService().menuCreate(getMenu());
    }

    private static void getJsapiTicket(WxMpService wxMpService) throws Exception {
        String jsapiTicket = wxMpService.getJsapiTicket(true);
        System.out.println("jsapiTicket = " + jsapiTicket);
    }

    private static void testSendTemplateMsg(WxMpService wxMpService) throws WxErrorException {
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss.SSS");
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                .toUser("on0z5wtrZyLP_IfHAj4q3qVMHdRY")
                .templateId("8G6XEB8N5B0lIJDIffZJiary5h8xMU-VYJnFk4j8IWg")
                .url("http://www.baidu.com")
                .build();
        templateMessage.addData(new WxMpTemplateData("userName", dateFormat.format(new Date()), "#FF00FF"))
                .addData(new WxMpTemplateData("courseName", "courseName张", "#FF00FF"))
                .addData(new WxMpTemplateData("date", "date时间", "#FF00FF"))
                .addData(new WxMpTemplateData("remark", RandomStringUtils.randomAlphanumeric(100), "#FF00FF"));
        String msgId = wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
        System.out.println(msgId);
    }

    private static void genSignature(WxMpService wxMpService) throws Exception {
//        noncestr=Wm3WZYTPz0wzccnW
//        jsapi_ticket=sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg
//        timestamp=1414587457
//        url=http://mp.weixin.qq.com?params=value
//        https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx91cb107f6dd2f0ba&redirect_uri=http://wenren.gcocp.com/index.html&response_type=code&scope=snsapi_base&state=#wechat_redirect
//        String accessToken = wxMpService.getAccessToken();
        String jsapiTicket = wxMpService.getJsapiTicket(true);
        String str = "jsapi_ticket=" + jsapiTicket + "&noncestr=1&timestamp=1&url=http://wenren.gcocp.com/wx/index";
        System.out.println("str = " + str);
        String gen = SHA1.gen(str);
        System.out.println("gen = " + gen);
    }

    public static class MainConfig {
        private String appId;
        private String appSecret;
        private String token;
        private String aesKey;

        /**
         * 为了生成自定义菜单使用的构造函数
         *
         * @param appId
         * @param appSecret
         * @param token
         * @param aesKey
         */
        protected MainConfig(String appId, String appSecret, String token, String aesKey) {
            this.appId = appId;
            this.appSecret = appSecret;
            this.token = token;
            this.aesKey = aesKey;
        }

        public WxMpConfigStorage wxMpConfigStorage() {
            WxMpInMemoryConfigStorage configStorage = new WxMpInMemoryConfigStorage();
            configStorage.setAppId(this.appId);
            configStorage.setSecret(this.appSecret);
            configStorage.setToken(this.token);
            configStorage.setAesKey(this.aesKey);
            return configStorage;
        }

        public WxMpService wxMpService() {
            WxMpService wxMpService = new WxMpServiceImpl();
            wxMpService.setWxMpConfigStorage(wxMpConfigStorage());
            return wxMpService;
        }

    }
}
